import numpy

from classfile.attributes import AttributeHelper, ConstantValue
from classfile.class_reader import ClassReader, AttributeData, ByteReader
from classfile.constant import ConstantPool, ConstantUTF8


class ClassMember:
    def __init__(self, cp: ConstantPool, br: ByteReader):
        # 常量池
        self.cp: ConstantPool = cp
        # 成员变量的访问标识
        self.accessFlags: numpy.uint16 = br.readUInt16()
        # 成员变量的名称
        self.nameIndex: numpy.uint16 = br.readUInt16()
        # 成员变量的类型描述符号
        self.descriptorIndex: numpy.uint16 = br.readUInt16()
        # 成员变量的属性如注解 等等信息
        self.attrs = []

    def readAttr(self, cr: ClassReader):
        size = cr.readUInt16()
        if size > 0:
            for i in range(0, size):
                attr = AttributeHelper.newAttr(cr=cr, cp=self.cp)
                self.attrs.append(attr)
        return self

    def getName(self) -> str:
        return self.cp.getConstant(index=int(self.nameIndex)).value

    def getDescriptor(self) -> str:
        return self.cp.getConstant(index=int(self.descriptorIndex)).value

    def getConstantValue(self) -> ConstantValue:
        for attr in self.attrs:
            if attr.attributeName.value == "ConstantValue":
                return attr
        return None


class Field(ClassMember):
    pass


class Method(ClassMember):

    def getCode(self):
        for attr in self.attrs:
            if attr.attributeName.value == "Code":
                return attr
        return None
